package com.redwine.app.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.redwine.app.APP;
import com.redwine.app.R;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by tian on 15/4/17:下午5:32.
 */
@SuppressWarnings({"unused", "SetJavaScriptEnabled"})
public class Utils {
    //qcl单例toast和主线程刷新ui
    private static Toast toast;

    /**
     * 在主线程中刷新UI的方法
     *
     * @param r
     */
    public static void runOnUIThread(Runnable r) {
        APP.getMainHandler().post(r);
    }

    public static void showToast(final int resId) {
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (toast == null) {
                    toast = Toast.makeText(APP.getInstance(), resId, Toast.LENGTH_SHORT);
                }
                toast.setText(resId);
                toast.setGravity(Gravity.CENTER, 0, 10);//设置toast显示位置
                toast.show();
            }
        });

    }


    //判断是否登录过，如果没有登录就跳转到登录界面
    public static void askLogIn(Activity activity) {
//        Intent intent = new Intent(activity, LogInActivity.class);
//        activity.startActivity(intent);
//        activity.overridePendingTransition(R.anim.activity_open, 0);
    }

    public static void showToast(final String msg) {
        Utils.runOnUIThread(new Runnable() {
            @Override
            public void run() {
                if (toast == null)

                {
                    toast = Toast.makeText(APP.getInstance(), msg, Toast.LENGTH_SHORT);
                }

                toast.setText(msg);
                toast.setGravity(Gravity.CENTER, 0, 10);
                toast.show();
            }
            //Toast.makeText(App.getInstance(), msg, Toast.LENGTH_SHORT).show();
            //qcl单例toast

        });
    }


    /**
     *          * 将sp值转换为px值，保证文字大小不变
     *          * 
     *          * @param spValue
     *          * @param fontScale
     *          *            （DisplayMetrics类中属性scaledDensity）
     *          * @return
     *          
     */
    public static int sp2px(float spValue) {
        final float fontScale = APP.getInstance().getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }


    //dp转px

    public static int dip2px(float dpValue) {
        final float scale = APP.getInstance().getResources().getDisplayMetrics().density;
        return (int) ((dpValue * scale) + 0.5f);
    }

    public static int dip2px(Context context, float dpValue) {
        //dip->px
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpValue,
                context.getResources().getDisplayMetrics());
    }


    public static String toHexString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String doubleBit = Integer.toHexString(b & 0xff);
            if (doubleBit.length() == 1) {
                hexString.append('0');
            }
            hexString.append(doubleBit);
        }
        return hexString.toString().toLowerCase();
    }

    public static String getEncryptedPassword(String password) {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            byte[] data = password.getBytes();
            return toHexString(m.digest(data));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return password;
        }
    }

    public static void makeCall(Context context, String number) {
        if (TextUtils.isEmpty(number)) {
            return;
        }
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel",
                    number, null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(context, "该设备不支持拨打电话功能", Toast.LENGTH_LONG).show();
        }
    }

    public static void closeKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    private static final String APP_CACAHE_DIRNAME = "/webcache";

    //针对三星等大屏幕分辨率设置webview
    public static void setSanxingWebSettings(Context mContext, WebView webview) {
        //        解决三星等高密度手机上网页放大问题开始
        int screenDensity = mContext.getResources().getDisplayMetrics().densityDpi;
        WebSettings.ZoomDensity zoomDensity = WebSettings.ZoomDensity.FAR;
        switch (screenDensity) {
            case DisplayMetrics.DENSITY_LOW://对应ldpi 320*240 分辨率
                zoomDensity = WebSettings.ZoomDensity.CLOSE;
                webview.getSettings().setDefaultZoom(zoomDensity);
                break;
            case DisplayMetrics.DENSITY_MEDIUM://对应mdpi 480*320分辨率
                zoomDensity = WebSettings.ZoomDensity.MEDIUM;
                webview.getSettings().setDefaultZoom(zoomDensity);
                break;
            case DisplayMetrics.DENSITY_HIGH://对应hdpi 480*800 分辨率
                zoomDensity = WebSettings.ZoomDensity.FAR;
                break;
            case DisplayMetrics.DENSITY_XHIGH://对应xhdpi 1280*720分辨率
                webview.setInitialScale(100);//
                break;
            case DisplayMetrics.DENSITY_XXHIGH://对应xxhdpi 1080*1920分辨率
                webview.setInitialScale(98);//
                break;
            case DisplayMetrics.DENSITY_XXXHIGH://对应xxxh分辨率，三星的分辨率大部分都是这个，所以问题基本上出在这里
                webview.setInitialScale(90);
                break;
        }
        webview.getSettings().setDefaultZoom(zoomDensity);
        // 解决三星等高密度手机上网页放大问题结束

    }


    //设置webview,带缓存
    public static void setDefaultWebSettings(WebView webview) {
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        //设置加载进来的页面自适应手机屏幕
        webview.getSettings().setUseWideViewPort(true);//可以任意缩放比例
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setDomStorageEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0以后兼容https和http
            webview.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);//
        }
        webview.getSettings().setJavaScriptEnabled(true);
        webview.getSettings().setUseWideViewPort(true);
        webview.getSettings().setLoadWithOverviewMode(true);
        //        //支持javascript
        //        webview.getSettings().setJavaScriptEnabled(true);
        //        // 设置禁止缩放工具
        //        webview.getSettings().setBuiltInZoomControls(false);
        //        webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        //
        //        //--------------从网上找到的webview功能---------------------------------
        //        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        //        webview.getSettings().setLoadsImagesAutomatically(true);  //支持自动加载图片


        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 开启 DOM storage API 功能
        webview.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        webview.getSettings().setDatabaseEnabled(true);
//        String cacheDirPath = APP.getInstance().getCacheDir() + APP_CACAHE_DIRNAME;
        //      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        //设置数据库缓存路径
//        webview.getSettings().setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
//        webview.getSettings().setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置 缓存模式
        webview.getSettings().setAppCacheEnabled(false);
        webview.getSettings().setAppCacheMaxSize(100 * 1024 * 1024);   //缓存最多可以有8M
        webview.getSettings().setAllowFileAccess(true);   // 可以读取文件缓存(manifest生效)


    }


    //设置webview
    public static void setDefaultWebSettings2(WebView webview) {
        webview.getSettings().setDefaultTextEncodingName("UTF-8");
        webview.getSettings().setUseWideViewPort(true);//可以任意缩放比例
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        //        //支持javascript
        //        webview.getSettings().setJavaScriptEnabled(true);
        //        // 设置禁止缩放工具
        webview.getSettings().setBuiltInZoomControls(false);
        webview.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);
        //
        //        //--------------从网上找到的webview功能---------------------------------
        //        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        //        webview.getSettings().setLoadsImagesAutomatically(true);  //支持自动加载图片


        ;


        webview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);  //设置 缓存模式
        // 开启 DOM storage API 功能
        webview.getSettings().setDomStorageEnabled(true);
        //开启 database storage API 功能
        webview.getSettings().setDatabaseEnabled(true);
        String cacheDirPath = APP.getInstance().getCacheDir() + APP_CACAHE_DIRNAME;
        //      String cacheDirPath = getCacheDir().getAbsolutePath()+Constant.APP_DB_DIRNAME;
        //设置数据库缓存路径
        webview.getSettings().setDatabasePath(cacheDirPath);
        //设置  Application Caches 缓存目录
        webview.getSettings().setAppCachePath(cacheDirPath);
        //开启 Application Caches 功能
        webview.getSettings().setAppCacheEnabled(false);

        webview.getSettings().setAppCacheMaxSize(100 * 1024 * 1024);   //缓存最多可以有8M
        webview.getSettings().setAllowFileAccess(true);   // 可以读取文件缓存(manifest生效)


    }


    //显示时间
    private static final long SECOND_GAP = 10 * 1000;
    private static final int MINUTE_MILLI = 60 * 1000;

    public static boolean isInSameMinute(long sendTime, long now) {
        return now - sendTime < MINUTE_MILLI;
    }

    private static final int HOUR_MILLI = 60 * 60 * 1000;

    public static boolean isInSameHour(long sendTime, long now) {
        return now - sendTime < HOUR_MILLI;
    }

    private static final int DAY_MILLI = 24 * 60 * 60 * 1000;

    public static boolean isInSameDAY(long sendTime, long now) {
        return now - sendTime < DAY_MILLI;
    }

    private static final int WEEK_MILLI = 7 * 24 * 60 * 60 * 1000;

    public static boolean isInSameWeek(long sendTime, long now) {
        return now - sendTime < WEEK_MILLI;
    }

    /*
    * 4.3新加6个月内只显示月日，6个月以上显示年月日，并且不显示作者名称
    * */
    public static String getDateString(long create_time) {
        Context context = APP.getInstance();
        long now = System.currentTimeMillis();
        long time = create_time * 1000;
        if (now - time < SECOND_GAP) {
            return context.getString(R.string.just_now);
        } else if (isInSameMinute(time, now)) {
            return (now - time) / 1000 + "秒前";
        } else if (isInSameHour(time, now)) {
            return (now - time) / 60 / 1000 + "分钟前";
        } else if (isInSameDAY(time, now)) {
            return (now - time) / 60 / 60 / 1000 + "小时前";
        } else if (isInSameWeek(time, now)) {
            return (now - time) / 24 / 60 / 60 / 1000 + "天前";
        } else if ((now - time) / 24 / 60 / 60 / 1000 > 180) {//大于6个月显示yyyy-MM-dd
            Date date = new Date(time);
            return String.valueOf(DateFormat.format("yyyy-MM-dd", date));//6个月前显示年月日
        } else {
            Date date = new Date(create_time * 1000);
            return String.valueOf(DateFormat.format("MM-dd", date));//6个月内显示月日
        }
    }


    //    3.0.5添加年月日显示
    public static String getDateString2(long create_time) {
        Context context = APP.getInstance();
        long now = System.currentTimeMillis();
        long time = create_time * 1000;
        Log.e("time", "create_time" + create_time);
        Log.e("time", "now" + now);
        Log.e("time", "time" + time);
        //        if (now - time < SECOND_GAP) {
        //            return context.getString(R.string.just_now);
        //        } else if (isInSameMinute(time, now)) {
        //            return (now - time) / 1000 + "秒前";
        //        } else if (isInSameHour(time, now)) {
        //            return (now - time) / 60 / 1000 + "分钟前";
        //        } else if (isInSameDAY(time, now)) {
        //            return (now - time) / 60 / 60 / 1000 + "小时前";
        //        } else if (isInSameWeek(time, now)) {
        //            return (now - time) / 24 / 60 / 60 / 1000 + "天前";
        //        } else {
        Date date = new Date(create_time * 1000);
        return String.valueOf(DateFormat.format("yyyy-MM-dd", date));
        //        }
    }

    //    3.0.5返回年月日时分如：2016-01-01 12:11
    public static String getDateString3(long create_time) {
        //        Context context = APP.getInstance();
        //        long now = System.currentTimeMillis();
        //        long time = create_time * 1000;
        //
        Date date = new Date(create_time * 1000);
        return String.valueOf(DateFormat.format("yyyy-MM-dd HH:mm", date));
        //        }
    }


    public static String getDateStringRight(long create_time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("MM-dd hh:mm");
        return sDateFormat.format(new Date(create_time * 1000));
    }

    public static String getDateStringYear(long create_time) {
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm");
        return sDateFormat.format(new Date(create_time * 1000));
    }

    public static boolean isHuxiuArticleUrl(Uri uri) {
        try {
            String host = uri.getHost();
            if (host.endsWith(".huxiu.com")) {
                List<String> segments = uri.getPathSegments();
                if (segments.size() >= 2 && segments.get(0).contentEquals("article")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }

    public static boolean huxiuUrlIntent(Uri uri) {
        try {
            String host = uri.getHost();
            if (host.endsWith(".huxiu.com")) {
                List<String> segments = uri.getPathSegments();
                if (segments.size() >= 2 && segments.get(0).contentEquals("article")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }


    public static boolean isHuxiuVipPay(Uri uri) {
        try {
            String host = uri.getHost();
            String url = uri.toString();
            if (host.endsWith(".huxiu.com")) {
                if (url.contains("/vip/pay")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }


    public static boolean isHuxiuAvars(Uri uri) {
        try {
            String host = uri.getHost();
            String url = uri.toString();
            if (host.endsWith(".huxiu.com")) {
                if (url.contains("/active/app_join")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }

    public static boolean isHuoDong(Uri uri) {
        try {
            String host = uri.getHost();
            String url = uri.toString();
            if (host.endsWith(".huxiu.com")) {
                if (url.contains("/active/content")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }


    public static boolean isHuxiuCommentUrl(Uri uri) {
        try {
            String host = uri.getHost();
            if (host.endsWith(".huxiu.com")) {
                List<String> segments = uri.getPathSegments();
                if (segments.size() >= 2 && segments.get(0).contentEquals("get_comment")) {
                    return true;
                }
            }
        } catch (Exception e) {
            //if NPE occurs, ignore it
        }
        return false;
    }


    public static void doCopy(String text) {
        ClipboardManager cm = (ClipboardManager) APP.getInstance()
                .getSystemService(Context.CLIPBOARD_SERVICE);
        cm.setPrimaryClip(ClipData.newPlainText("", text));
    }


    public static String getDeviceInfo(Context context) {
        if (context != null) {
            try {
                org.json.JSONObject json = new org.json.JSONObject();
                android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                        .getSystemService(Context.TELEPHONY_SERVICE);

                String device_id = tm.getDeviceId();

                android.net.wifi.WifiManager wifi = (android.net.wifi.WifiManager) context.getSystemService(Context.WIFI_SERVICE);

                String mac = wifi.getConnectionInfo().getMacAddress();
                json.put("mac", mac);

                if (TextUtils.isEmpty(device_id)) {
                    device_id = mac;
                }

                if (TextUtils.isEmpty(device_id)) {
                    device_id = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
                }

                json.put("device_id", device_id);

                return json.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
        return null;
    }

    public static String SubString(String str) {
        if (TextUtils.isEmpty(str)) {
            return "";
        }
        if (str.length() > 138) {
            return str.substring(0, 138);
        }
        return str;
    }

    /**
     * 使用java正则表达式去掉多余的.与0
     *
     * @param s
     * @return
     */
    public static String subZeroAndDot(String s) {
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }

    //浏览量万以上显示万+
    public static String getSeeNumToStr(int num) {
        if (num >= 10000) {
            return "1万+";
        } else if (num >= 20000) {
            return "2万+";
        } else if (num >= 30000) {
            return "3万+";
        } else if (num >= 40000) {
            return "4万+";
        } else if (num >= 50000) {
            return "5万+";
        } else if (num >= 60000) {
            return "6万+";
        } else if (num >= 70000) {
            return "7万+";
        } else if (num >= 80000) {
            return "8万+";
        } else {
            return Integer.toString(num);
        }
    }


    public static String getVersionName(Context mContext) {
        try {
            String pkName = mContext.getPackageName();
            String versionName = mContext.getPackageManager().getPackageInfo(
                    pkName, 0).versionName;
            int versionCode = mContext.getPackageManager()
                    .getPackageInfo(pkName, 0).versionCode;
            return versionName;
        } catch (Exception e) {
        }
        return "3.0.1";
    }


    public static String pkName(Context mContext) {
        String pkName = mContext.getPackageName();
        return pkName;
    }

    //    public static <T>List<T> getPersons(String jsonString,Class<T> cls) {
    //            List<T> list = new ArrayList<T>();
    //            try {
    //                Gson gson = new Gson();
    //                list = gson.fromJson(jsonString, new TypeToken<>() {
    //                }.getType());
    //            } catch (Exception e) {
    //            }
    //            return list;
    //        }


    public static List<Map<String, Object>> listKeyMaps(String jsonString) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        try {
            Gson gson = new Gson();
            list = gson.fromJson(jsonString,
                    new TypeToken<List<Map<String, Object>>>() {
                    }.getType());
        } catch (Exception e) {
        }
        return list;
    }


    public static <T> T getPerson(String jsonString, Class<T> cls) {
        T t = null;
        try {
            Gson gson = new Gson();
            t = gson.fromJson(jsonString, cls);
        } catch (Exception e) {
        }
        return t;
    }

    //隐藏键盘
    public static void HidInput(EditText edit, Activity instance) {
        InputMethodManager imm = (InputMethodManager) instance.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(edit.getWindowToken(), 0);
    }

    /**
     * 键盘没有打开就显示否则就关闭
     *
     * @param v
     */
    public static void toggleSoftInput(final View v, final Context context) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 100);
    }

    /**
     * 写个去除数组中重复数据的方法
     */
    public static String[] array_unique(String[] a)

    {

        // array_unique

        List<String> list = new LinkedList<String>();

        for (int i = 0; i < a.length; i++) {

            if (!list.contains(a[i]))

            {
                list.add(a[i]);

            }
        }

        return (String[]) list.toArray(new String[list.size()]);

    }

    public static List<String> removeDuplicateWithOrder(List<String> list) {
        Set set = new HashSet();
        List newList = new ArrayList();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object element = iter.next();
            if (set.add(element))
                newList.add(element);
        }
        list.clear();
        list.addAll(newList);
        return list;
    }


    public static boolean getIsSaleTicketState(long startTime, long endTime, int pricenum) {
        Log.e("getIsSaleTicketState", "startTime" + startTime);
        Log.e("getIsSaleTicketState", "endTime" + endTime);
        Log.e("getIsSaleTicketState", "nowtime" + getNowTime() / 1000);
        if (pricenum <= 0) {
            return false;
        }
        if (getNowTime() / 1000 <= endTime && getNowTime() >= startTime) {
            return true;
        } else {
            return false;
        }
    }


    public static long getNowTime() {
        Date dt = new Date();
        long nowtime = dt.getTime();
        return nowtime;
    }


    public static boolean isEmpty(Object obj) {
        if (null == obj)
            return true;
        else if (obj == "")
            return true;
        else if (obj instanceof Integer || obj instanceof Long
                || obj instanceof Double) {
            // if((Integer.parseInt(obj.toString()))==0) return bool;
            try {
                Double.parseDouble(obj + "");
            } catch (Exception e) {
                return true;
            }
        } else if (obj instanceof String) {
            if (((String) obj).length() <= 0)
                return true;
            if ("null".equals(obj))
                return true;
        } else if (obj instanceof Map) {
            if (((Map) obj).size() == 0)
                return true;
        } else if (obj instanceof Collection) {
            if (((Collection) obj).size() == 0)
                return true;
        }
        return false;
    }


    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static byte[] getHtmlByteArray(final String url) {
        URL htmlUrl = null;
        InputStream inStream = null;
        try {
            htmlUrl = new URL(url);
            URLConnection connection = htmlUrl.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            int responseCode = httpConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                inStream = httpConnection.getInputStream();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] data = inputStreamToByte(inStream);

        return data;
    }


    public static byte[] inputStreamToByte(InputStream is) {
        try {
            ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
            int ch;
            while ((ch = is.read()) != -1) {
                bytestream.write(ch);
            }
            byte imgdata[] = bytestream.toByteArray();
            bytestream.close();
            return imgdata;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    //    v3.2新加优化大图片setBackgroundResource内存溢出问题
    public static BitmapDrawable readBigBitMap(Context context, int resId) {
        BitmapFactory.Options options = new BitmapFactory.Options();//Options 只保存图片尺寸大小，不保存图片到内存
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inSampleSize = 10;   //width，hight设为原来的十分一
        //获取资源图片
        InputStream is = context.getResources().openRawResource(resId);
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, options);
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new BitmapDrawable(context.getResources(), bitmap);
    }


    public static boolean isGif(String url) {
        if (TextUtils.isEmpty(url)) {
            return false;
        }
        url.toLowerCase();
        return url.endsWith(".gif");
    }

    public static boolean checkPhone(String phone) {
        Pattern pattern = Pattern.compile("^13/d{9}||15[8,9]/d{8}$");
        Matcher matcher = pattern.matcher(phone);

        if (matcher.matches()) {
            return true;
        }
        return false;
    }

    private static DecimalFormat decimalFormat = new DecimalFormat(".#");//DecimalFormat对数字进行格式化

    public static float formatFloatPoint(float mValue) {
        if (mValue < 0) {
            return 0;
        }
        float newValue = 0;//设置增益参数
        try {
            newValue = Float.parseFloat(decimalFormat.format(mValue));
        } catch (Exception e) {

        }
        if (newValue >= 0.9f) {
            return 1;
        } else {
            return newValue;
        }
    }

    /**
     * 判断list是否为空
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T> boolean isListEmpty(List<T> list) {
        if (list == null || list.size() <= 0) {
            return true;
        }
        return false;
    }

    private static long lastClickTime;

    /**
     * 检测是否小于一定毫秒数疯狂点击
     *
     * @return true表示小于，需要return处理 eg: if (Utils.isFastClick()){ return ; }
     * @times 希望的毫秒间隔，不传默认为600毫秒
     */
    public static synchronized boolean isFastClick(long... times) {
        long intervalTime = 600;
        if (null != times && times.length > 0) {
            intervalTime = times[0];
        }
        long time = System.currentTimeMillis();
        if (time - lastClickTime < intervalTime) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public static void IntentParams(Intent intent, View mView) {
        float x = mView.getX();
        float y = mView.getY();
        int hight = mView.getHeight();
        Log.e("hahahhahahhahah", "px" + x + "py" + y + "phight" + hight);
        intent.putExtra(Constants.KEY_X, x);
        intent.putExtra(Constants.KEY_Y, y);
        intent.putExtra(Constants.KEY_HIGHT, hight);
    }

    private static SimpleDateFormat dataFormatUtils = new SimpleDateFormat("HH:mm:ss");

    public static String getNowTimeFormat() {
        String time = "";
        try {
            Date dt = new Date();
            time = dataFormatUtils.format(dt);
        } catch (Exception e) {

        }
        return time;
    }


    public static String getStringFromAssert(Context mContext, String fileName) throws IOException {
        String content = null; //结果字符串 
        InputStream is = mContext.getResources().getAssets().open(fileName); //打开文件 
        int ch = 0;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while ((ch = is.read()) != -1) {
            out.write(ch); //将指定的字节写入此 byte 数组输出流 
            byte[] buff = out.toByteArray();//以 byte 数组的形式返回此输出流的当前内容 
            out.close(); //关闭流 
            is.close(); //关闭流 
            content = new String(buff, "UTF-8"); //设置字符串编码 
        }
        return content;
    }

    /**
     * 实现文本复制功能
     * add by wangqianzhou
     *
     * @param content
     */
    public static void copy(String content, Context context) {
// 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }

    /**
     * 实现粘贴功能
     * add by wangqianzhou
     *
     * @param context
     * @return
     */
    public static String paste(Context context) {
// 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        return cmb.getText().toString().trim();
    }


    /*
  * 把 123.html提取出数字123
  * */
    public static String getIdFromUrl(String idStr) {
        if (!TextUtils.isEmpty(idStr)) {
            Pattern pattern = Pattern.compile("[^0-9]");
            Matcher matcher = pattern.matcher(idStr);
            String all = matcher.replaceAll("");
            return all;
        } else {
            return idStr;
        }
    }


    /**
     * 设置采购状态
     * 1 采购中 2已关闭 3审核中 4审核失败 5 交易成功 6删除7停止采购
     *
     * @param textView
     * @param status
     */
    public static void setProcurementStatus(TextView textView, int status) {
        switch (status) {

            case 1:
                textView.setText("采购中");
                break;

            case 2:
                textView.setText("已关闭");
                break;

            case 3:
                textView.setText("审核中");
                break;

            case 4:
                textView.setText("审核失败");
                break;

            case 5:
                textView.setText("交易成功");
                break;

            case 6:
                textView.setText("已删除");
                break;

            case 7:
                textView.setText("停止采购");
                break;

        }
    }


    /**
     * 设置供应商状态
     * 1 审核中  2 审核失败 3 交易成功 4 过期 5 展示中 审核成功 6 删除 7停止供应
     *
     * @param textView
     * @param status
     */
    public static void setSupplierStatus(TextView textView, int status) {
        switch (status) {

            case 1:
                textView.setText("审核中");
                break;

            case 2:
                textView.setText("审核失败");
                break;

            case 3:
                textView.setText("交易成功");
                break;

            case 4:
                textView.setText("过期");
                break;

            case 5:
                textView.setText("供应中");
                break;

            case 6:
                textView.setText("已删除");
                break;

            case 7:
                textView.setText("停止供应");
                break;

        }
    }


    /**
     * 设置认证状态
     * 0默认  1 申请中 2 失败 3驳回 4成功
     *
     * @param textView
     * @param status
     */
    public static boolean setCertificationStatus(TextView textView, String status) {

        if (TextUtils.isEmpty(status)) {
            if (null != textView)
                textView.setText("");
            return false;
        }

        switch (Integer.valueOf(status)) {

            case 1:
                if (null != textView)
                    textView.setText("认证中");
                return true;

            case 2:
                if (null != textView)
                    textView.setText("认证失败");
                return false;

            case 3:
                if (null != textView)
                    textView.setText("认证驳回");
                return false;

            case 4:
                if (null != textView)
                    textView.setText("认证成功");
                return true;

            default:
                if (null != textView)
                    textView.setText("");
                return false;
        }
    }

    /**
     * 设置显示时间
     *
     * @param textView
     * @param dataEntityRemain
     */
    public static void setShowTime(TextView textView, String dataEntityRemain) {
        int day = -1;
        int hour = -1;
        SpannableString sStr = new SpannableString(dataEntityRemain);
        if (dataEntityRemain.contains("天")) {
            day = dataEntityRemain.indexOf("天");
            sStr.setSpan(new ForegroundColorSpan(Color.parseColor("#E82565")), 0, day, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        if (dataEntityRemain.contains("小时")) {
            hour = dataEntityRemain.indexOf("小时");
            if (day != -1) {
                sStr.setSpan(new ForegroundColorSpan(Color.parseColor("#E82565")), day + 1, hour, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                sStr.setSpan(new ForegroundColorSpan(Color.parseColor("#E82565")), 0, hour, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        if (dataEntityRemain.contains("分")) {
            int minute = dataEntityRemain.indexOf("分");
            if (hour != -1) {
                sStr.setSpan(new ForegroundColorSpan(Color.parseColor("#E82565")), hour + 2, minute, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            } else {
                sStr.setSpan(new ForegroundColorSpan(Color.parseColor("#E82565")), 0, minute, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        textView.setText(sStr);
    }


    /**
     * 传递一个，分割的字符串返回一个集合
     *
     * @param content
     * @return
     */
    public static List<String> strConvertList(String content) {
        List<String> list = new ArrayList<>();
        if (!TextUtils.isEmpty(content)) {
            String[] split = content.split(",");
            for (int i = 0; i < split.length; i++) {
                list.add(split[i]);
            }
            return list;
        } else {
            return new ArrayList<>();
        }
    }


}
